package upload.demo.vue_springboot_upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.corundumstudio.socketio.SocketIOServer;
//import org.springframework.core.io.*;

import jakarta.annotation.Resource;


@CrossOrigin(origins="http://localhost:5173")
@RestController
public class FileUploadController {
	
	@Resource
	private SocketIOServer socketIOServer;
	
	
	@PostMapping("/upload")
	public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file,
	                                     @RequestHeader(value = "Content-Range", required = false) String contentRange) throws IOException {
	    // Parse the Content-Range header to get the range of bytes being uploaded
	    long start = 0;
	    long end = file.getSize();
	    long fileSize = 0;
	    if (contentRange != null) {
	        String[] range = contentRange.split(" ")[1].split("/")[0].split("-");
	        String fileSizeStr = contentRange.split(" ")[1].split("/")[1];
	        start = Long.parseLong(range[0]);
	        end = Long.parseLong(range[1]);
	        fileSize = Long.parseLong(fileSizeStr);
	    }

	    // Save the chunk to a temporary file
	    File tempFile = new File("/Users/shirongxin/tmp/upload/temp-file");
	    try (RandomAccessFile raf = new RandomAccessFile(tempFile, "rw")) {
	        raf.seek(start);
	        raf.write(file.getBytes());
	    } catch (IOException e) {
	        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	    }

	    // Emit an event via Socket.IO when the upload is complete
	    if (end == fileSize) {
	        socketIOServer.getBroadcastOperations().sendEvent("fileUploaded", "http://localhost:8080/download?fileName=temp-file");
	    }

	    return ResponseEntity.ok().build();
	}


	@GetMapping("/download")
	public ResponseEntity<org.springframework.core.io.Resource> downloadFile(@RequestParam("fileName") String fileName) throws FileNotFoundException {
	  File file = new File("/Users/shirongxin/tmp/upload/" + fileName);
	  InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

	  HttpHeaders headers = new HttpHeaders();
	  headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
	  headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");

	  return ResponseEntity.ok()
	      .headers(headers)
	      .contentLength(file.length())
	      .body(resource);
	}
	


}
